#include<iostream>
#include<pthread.h>
#include<vector>
#include<unistd.h>
#include<cstdio>
#include<string.h>
#include"mutex.hpp"
using namespace std;

int tickets = 1000;//多线程模拟抢票

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

#define NUM 4

class ThreadData
{
public:
    ThreadData(int number)
    {
        _threadname = "thread-"+ to_string(number);
    }

public:
    string _threadname;
};

// class ThreadData
// {
// public:
//     ThreadData(int number,  pthread_mutex_t *mutex)
//     {
//         _threadname = "thread-"+ to_string(number);
//         _lock = mutex;
//     }

// public:
//     string _threadname;
//     pthread_mutex_t *_lock;
// };


// void* GetTicket(void *args)
// {
//     ThreadData *td = static_cast<ThreadData *>(args);
//     const char *name = td->_threadname.c_str();
//     int cnt = 5;
//     while(true)
//     {
//         pthread_mutex_lock(&lock);
//         if(tickets > 0)
//         {
//             usleep(1000);
//             printf("who = %s, get a ticket : %d\n", name, tickets);
//             tickets--;
//             pthread_mutex_unlock(&lock);
//         }
//         else
//         {
//             pthread_mutex_unlock(&lock);
//             break;
//         }
//         usleep(13);

//     }
//     return nullptr;
// }

void* GetTicket(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    const char *name = td->_threadname.c_str();
    int cnt = 5;
    while(true)
    {
        LockGuard lockguard(&lock);
        if(tickets > 0)
        {
            usleep(1000);
            printf("who = % s, get a ticket : %d\n", name, tickets);
            tickets--;
        }
        else
            break;
        usleep(13);

    }
    return nullptr;
}


int main()
{

    // pthread_mutex_init(&lock, nullptr);

    vector<pthread_t> tids;
    vector<ThreadData*>thread_datas;
    for(int i = 1; i <= NUM; i++)
    {
        pthread_t tid;
        ThreadData *td = new ThreadData(i);
        thread_datas.push_back(td);
        pthread_create(&tid, nullptr, GetTicket, td);
        tids.push_back(tid);
    }

    for(auto thread: tids)
    {
        pthread_join(thread, nullptr);
    }
    for(auto td: thread_datas)
    {
        delete td;
    }
    //关锁
    // pthread_mutex_destroy(&lock);
    return 0;
}
